package com.jerry.usbserial.fragment.udp

import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import com.jerry.usbserial.R
import com.jerry.usbserial.util.showToast
import com.jerry.usbserial.util.task.udp.UDPWifiConfigTask
import kotlinx.android.synthetic.main.bar_common.*
import kotlinx.android.synthetic.main.frg_normal_config.*

class NormalConfigFragment : UdpFragment() {
    private var isDeviceWifi = false

    override val layoutId: Int = R.layout.frg_normal_config

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        toolbar_title.text = "手动配网"

        bt_device_wifi.setOnClickListener {
            isDeviceWifi = true
            startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
        }
        bt_start.setOnClickListener {
            val ssid = et_ssid.text.toString()
            val password = et_password.text.toString()
            if (ssid.isEmpty()) {
                context!!.showToast("请连接设备待连接WIFI")
                return@setOnClickListener
            }
            if (password.isEmpty()) {
                context!!.showToast("请输入密码")
                return@setOnClickListener
            }

            bt_start.isEnabled = false
            isDeviceWifi = false
            UDPWifiConfigTask(ssid, password).apply {
                setOnResultListener { msg ->
                    activity!!.runOnUiThread {
                        if (!msg.isNullOrEmpty()) context!!.showToast(msg)
                        bt_start.isEnabled = true

                    }
                }
                start()
            }
        }
    }

    override fun handlerResult(ssid: String?, bssid: String?, ip: String?, error: String?) {
        Log.d("TAG", "handlerResult: $ip")
        if (!error.isNullOrEmpty()) {
            tv_message.text = error
            tv_message.setTextColor(resources.getColor(R.color.error))
            if (isDeviceWifi) {
                bt_start.visibility = View.GONE
            }
            return
        }
        if (!isDeviceWifi) {
            et_ssid.setText(ssid ?: "")
        } else {
            if (et_ssid.text.toString() == ssid) {
                return
            }
            if (ip?.startsWith("192.168.4.") == true) {
                bt_start.visibility = View.VISIBLE
            } else {
                tv_message.text = "请检查是否连接到设备wifi"
                tv_message.setTextColor(resources.getColor(R.color.error))
                return
            }
            tv_message.text = "已经连接到设备WIFI: $ssid"
            tv_message.setTextColor(resources.getColor(R.color.white))

        }
    }
}